package com.fhc.view

import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.*
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.dp
data class SelectOption(
    val label: String,
    val value: String
)

enum class SelectSize {
    SMALL, DEFAULT, LARGE
}

@Composable
fun TagsSelect(
    modifier: Modifier = Modifier,
    placeholder: String = "Please select",
    value: List<SelectOption>,
    onValueChange: (List<SelectOption>) -> Unit,
    options: List<SelectOption>,
    borderColor: Color = Color.Gray,
    textColor: Color = Color.Gray,
    size: SelectSize = SelectSize.DEFAULT,
    enabled: Boolean = true,
    width: Int = 200,
    height: Int = 64
) {
    var expanded by remember { mutableStateOf(false) }
    var searchText by remember { mutableStateOf(TextFieldValue("")) }

    var hasValue by remember { mutableStateOf(false) }
    Box(
        modifier = modifier
            .width(width.dp)
            .height(height.dp)
            .background(
                Color.Transparent
            ).drawWithContent {
                drawContent()
                val bounds = this.size // 显式获取 size
                val strokeWidth = 2.dp.toPx()
                drawLine(
                    color = borderColor,
                    start = Offset(0f, bounds.height),
                    end = Offset(bounds.width, bounds.height),
                    strokeWidth = strokeWidth
                )
            }
            .clickable(enabled = enabled) {
                expanded = true
            }
    ) {
        if(!hasValue){
        Text(modifier = Modifier.fillMaxWidth().fillMaxHeight()
            .padding(start = 8.dp, end = 44.dp).wrapContentHeight(align = Alignment.CenterVertically),
            text = placeholder,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis, // 当文字超出时显示省略号
            softWrap = false, // 不换行
            color = textColor
            )}
        Column {
            // 已选标签显示区域
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(4.dp)
                    .height(height.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 使用自定义 TagLayout 处理标签显示
                TagLayout(
                    textColor = textColor,
                    tags = value,
                    onRemoveTag = { index ->
                        val newList = value.toMutableList().apply { removeAt(index) }
                        onValueChange(newList)
                        hasValue = newList.isNotEmpty()
                    },
                    size = size,
                    enabled = enabled,
                    modifier = Modifier.weight(1f)
                )

//                // 输入框  会导致availableWidth 短很多
//                TextField(
//                    value = searchText,
//                    onValueChange = {
//                        searchText = it
//                        expanded = true
//                    },
//                    modifier = Modifier
//                        .weight(1f)
//                        .onFocusChanged { focusState ->
//                            textFieldFocusState = focusState.isFocused
//                            if (focusState.isFocused) {
//                                expanded = true
//                            }
//                        },
//                    placeholder = {
//                        if (value.isEmpty()) {
//                            Text(
//                                text = placeholder,
//                                style = when (size) {
//                                    SelectSize.SMALL -> MaterialTheme.typography.bodySmall
//                                    SelectSize.DEFAULT -> MaterialTheme.typography.bodyMedium
//                                    SelectSize.LARGE -> MaterialTheme.typography.bodyLarge
//                                }
//                            )
//                        }
//                    },
//                    textStyle = when (size) {
//                        SelectSize.SMALL -> MaterialTheme.typography.bodySmall
//                        SelectSize.DEFAULT -> MaterialTheme.typography.bodyMedium
//                        SelectSize.LARGE -> MaterialTheme.typography.bodyLarge
//                    },
//                    colors = TextFieldDefaults.colors(
//                        focusedIndicatorColor = Color.Transparent,
//                        unfocusedIndicatorColor = Color.Transparent,
//                        disabledIndicatorColor = Color.Transparent,
//                        focusedContainerColor = Color.Transparent,
//                        unfocusedContainerColor = Color.Transparent,
//                        disabledContainerColor = Color.Transparent
//                    ),
//                    enabled = enabled,
//                    singleLine = true
//                )

                // 下拉箭头
                IconButton(
                    onClick = {
                        if (enabled) expanded = !expanded
                    },
                    modifier = Modifier.size(24.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.ArrowDropDown,
                        contentDescription = "",
                        tint = borderColor
                    )
                }
            }

            // 下拉选项菜单
            DropdownMenu(
                expanded = expanded && enabled,
                onDismissRequest = { expanded = false },
                modifier = Modifier
                    .width(width.dp)
                    .background(colorScheme.surface)
            ) {
                val filteredOptions = if (searchText.text.isBlank()) {
                    options
                } else {
                    options.filter {
                        it.label.contains(searchText.text, ignoreCase = true) ||
                                it.value.contains(searchText.text, ignoreCase = true)
                    }
                }

                if (filteredOptions.isEmpty()) {
                    DropdownMenuItem(
                        text = { Text("No data") },
                        onClick = { /* Do nothing */ },
                        enabled = false
                    )
                } else {
                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(200.dp)
                            .verticalScroll(rememberScrollState()),
                        verticalArrangement = Arrangement.spacedBy(4.dp)
                    ) {
                        filteredOptions.forEach { option ->
                            val isSelected = value.any { it.value == option.value }

                            DropdownMenuItem(
                                text = {
                                    Text(
                                        text = option.label,
                                        style = when (size) {
                                            SelectSize.SMALL -> MaterialTheme.typography.bodySmall
                                            SelectSize.DEFAULT -> MaterialTheme.typography.bodyMedium
                                            SelectSize.LARGE -> MaterialTheme.typography.bodyLarge
                                        }
                                    )
                                },
                                onClick = {
                                    if (isSelected) {
                                        // 取消选择
                                        val newList = value.filterNot { it.value == option.value }
                                        onValueChange(newList)

                                        hasValue = newList.isNotEmpty()
                                    } else {
                                        // 添加选择
                                        val newList = value + option
                                        onValueChange(newList)
                                        hasValue = newList.isNotEmpty()
                                    }
                                    // 清空搜索文本
                                    searchText = TextFieldValue("")
                                },
                                leadingIcon = {
                                    if (isSelected) {
                                        Icon(
                                            imageVector = Icons.Default.Check,
                                            contentDescription = "Selected",
                                            modifier = Modifier.size(16.dp)
                                        )
                                    }
                                }
                            )
                        }

                        // 支持添加新标签（tags模式）
                        if (searchText.text.isNotBlank() &&
                            filteredOptions.none { it.label == searchText.text }) {
                            HorizontalDivider(
                                modifier = Modifier.padding(vertical = 8.dp),
                                thickness = DividerDefaults.Thickness,
                                color = DividerDefaults.color
                            )
                            DropdownMenuItem(
                                text = {
                                    Text(
                                        text = "Add '${searchText.text}'",
                                        color = colorScheme.primary
                                    )
                                },
                                onClick = {
                                    val newOption = SelectOption(
                                        label = searchText.text,
                                        value = searchText.text
                                    )
                                    val newList = value + newOption
                                    onValueChange(newList)
                                    searchText = TextFieldValue("")
                                    expanded = false
                                }
                            )
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun TagLayout(
    modifier: Modifier = Modifier,
    textColor: Color = Color.Gray,
    tags: List<SelectOption>,
    onRemoveTag: (Int) -> Unit,
    size: SelectSize,
    enabled: Boolean,
) {
    Layout(
        content = {
            tags.forEachIndexed { index, tag ->
                TagItem(
                    tag = tag,
                    onRemove = { onRemoveTag(index) },
                    size = size,
                    enabled = enabled
                )
            }

            // 省略号文本
            if (tags.isNotEmpty()) {
                Text(
                    text = "...",
                    color = textColor,
                    style = when (size) {
                        SelectSize.SMALL -> MaterialTheme.typography.bodySmall
                        SelectSize.DEFAULT -> MaterialTheme.typography.bodyMedium
                        SelectSize.LARGE -> MaterialTheme.typography.bodyLarge
                    },
                    maxLines = 1,
                    modifier = Modifier
                )
            }
        },
        modifier = modifier
    ) { measurables, constraints ->
        // 获取实际可用的约束，避免极端值
        val maxWidth = constraints.maxWidth.coerceIn(0, 10000)
        val maxHeight = constraints.maxHeight.coerceIn(0, 10000)

        // 使用更保守的约束范围
        val safeConstraints = Constraints(
            minWidth = 0,
            maxWidth = maxWidth,
            minHeight = 0,
            maxHeight = maxHeight.coerceAtMost(100) // 标签区域不需要太高
        )

        // 更合理的空间分配
        val reservedSpace = 24.dp.roundToPx() // 仅预留箭头所需空间
        val availableWidth = (maxWidth - reservedSpace)
            .coerceAtLeast(40) // 至少保留40px空间显示标签

        val tagMeasurables = measurables.dropLast(if (tags.isNotEmpty()) 1 else 0)
        val ellipsisMeasurable = measurables.lastOrNull()?.takeIf { tags.isNotEmpty() }

        // 测量标签和省略号
        val tagPlaceables = tagMeasurables.map { it.measure(safeConstraints) }
        val ellipsisPlaceable = ellipsisMeasurable?.measure(
            Constraints(
                minWidth = 0,
                maxWidth = maxWidth,
                minHeight = 0,
                maxHeight = maxHeight
            )
        )

        // 计算实际需要的高度
        val tagHeight = when (size) {
            SelectSize.SMALL -> 20.dp
            SelectSize.DEFAULT -> 24.dp
            SelectSize.LARGE -> 32.dp
        }.roundToPx()

        // 使用固定的合理高度
        val layoutHeight = tagHeight.coerceIn(24, 40)

        layout(maxWidth, layoutHeight) {
            var xPos = 0
            val yPos = (layoutHeight - tagHeight) / 2

            var visibleTagCount = 0

            // 测量并放置可见的标签
            for ((_, placeable) in tagPlaceables.withIndex()) {
                if (xPos + placeable.width <= availableWidth) {
                    placeable.placeRelative(xPos, yPos)
                    xPos += placeable.width + 8 // 8dp 间距
                    visibleTagCount++
                } else {
                    break
                }
            }

            // 如果有隐藏的标签，放置省略号
            if (visibleTagCount < tags.size && ellipsisPlaceable != null) {
                ellipsisPlaceable.placeRelative(
                    xPos,
                    yPos + tagHeight / 2 - ellipsisPlaceable.height / 2
                )
            }
        }
    }
}



@Composable
private fun TagItem(
    textColor: Color = Color.Gray,
    tag: SelectOption,
    onRemove: () -> Unit,
    size: SelectSize,
    enabled: Boolean
) {
    Surface(
        modifier = Modifier
            .height(
                when (size) {
                    SelectSize.SMALL -> 28.dp
                    SelectSize.DEFAULT -> 36.dp
                    SelectSize.LARGE -> 44.dp
                }
            ),
        shape = RoundedCornerShape(when (size) {
            SelectSize.SMALL -> 4.dp
            SelectSize.DEFAULT -> 6.dp
            SelectSize.LARGE -> 8.dp
        }),
        color = colorScheme.primaryContainer
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.border(
                width = 2.dp,
                color = textColor,
                shape = RoundedCornerShape(8.dp)
            ).background(textColor.copy(alpha = 0.2f)).padding(horizontal = 16.dp)
        ) {
            Text(
                text = tag.label,
                color = textColor,
                style = when (size) {
                    SelectSize.SMALL -> MaterialTheme.typography.bodySmall
                    SelectSize.DEFAULT -> MaterialTheme.typography.bodyMedium
                    SelectSize.LARGE -> MaterialTheme.typography.bodyLarge
                },
                maxLines = 1
            )

            if (enabled) {
                Spacer(Modifier.width(4.dp))
                IconButton(
                    onClick = onRemove,
                    modifier = Modifier
                        .size(20.dp)
                        .padding(0.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.Close,
                        contentDescription = "Remove",
                        tint = colorScheme.onPrimaryContainer,
                        modifier = Modifier.size(16.dp)
                    )
                }
            }
        }
    }
}

@Preview(showBackground = true)
@Composable
fun TagsSelectDemo() {
    var selectedValues by remember { mutableStateOf<List<SelectOption>>(emptyList()) }

    val options = listOf(
        SelectOption("Option 1", "1"),
        SelectOption("Option 2", "2"),
        SelectOption("Option 3", "3"),
        SelectOption("Long Option Name", "4")
    )

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)
    ) {
        Text(
            text = "Tags Select Demo",
            style = MaterialTheme.typography.headlineSmall,
            modifier = Modifier.padding(bottom = 16.dp)
        )

        TagsSelect(
            value = selectedValues,
            onValueChange = { selectedValues = it },
            options = options,
            size = SelectSize.DEFAULT,
            width = 200
        )

        Spacer(Modifier.height(16.dp))

        Text(
            text = "Selected values: ${selectedValues.joinToString(", ") { it.label }}",
            style = MaterialTheme.typography.bodyMedium
        )
    }
}